const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const EslintWebpackPlugin = require('eslint-webpack-plugin')
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin')

const getStyleLoaders = pre =>
  [
    'style-loader',
    'css-loader',
    {
      loader: 'postcss-loader',
      options: {
        postcssOptions: {
          plugins: ['postcss-preset-env']
        }
      }
    },
    pre
  ].filter(Boolean)

module.exports = {
  entry: './src/main.js',
  output: {
    path: undefined,
    filename: 'static/js/[name].js',
    chunkFilename: 'static/js/[name].chunk.js',
    assetModuleFilename: 'static/media/[name][ext][query]'
  },
  module: {
    rules: [
      { test: /\.css$/, use: getStyleLoaders() },
      { test: /\.less$/, use: getStyleLoaders('less-loader') },
      { test: /\.s[ac]ss$/, use: getStyleLoaders('sass-loader') },
      { test: /\.styl$/, use: getStyleLoaders('stylus-loader') },
      { test: /\.(jpe?g|png|gif|svg|webp)$/, type: 'asset', parser: { dataUrlCondition: { maxSize: 10 * 1024 } } },
      { test: /\.(woff2?|ttf)$/, type: 'asset/resource' },
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        include: path.resolve(__dirname, '../src'),
        options: { cacheDirectory: true, cacheCompression: false, plugins: ['react-refresh/babel'] }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'webpack react cli',
      template: path.resolve(__dirname, '../public/index.html')
    }),
    new EslintWebpackPlugin({
      context: path.resolve(__dirname, '../src'),
      exclude: 'node_modules',
      cache: true,
      cacheLocation: path.resolve(__dirname, '../node_modules/.cache/eslintcache')
    }),
    new ReactRefreshWebpackPlugin()
  ],
  optimization: {
    splitChunks: {
      chunks: 'all'
    },
    runtimeChunk: {
      name: entrypoint => `runtime~${entrypoint.name}`
    }
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json']
  },
  devServer: {
    host: 'localhost',
    port: 3000,
    open: true,
    hot: true,
    historyApiFallback: true
  },
  mode: 'development',
  devtool: 'cheap-module-source-map'
}
